package com.bitantenna.messages;

import java.net.InetAddress;
import java.net.UnknownHostException;

import com.bitantenna.Message;
import com.bitantenna.PortAddress;



public class MessageAttachConsumer extends Message {


	@Override
	public void fromBytes(byte[] input) {
		byte a1=(byte)Message.paramFromPacket(input, 2);
		byte a2=(byte)Message.paramFromPacket(input, 3);
		byte a3=(byte)Message.paramFromPacket(input, 4);
		byte a4=(byte)Message.paramFromPacket(input, 5);
		
		
		try { //TODO ojo que usa un nuevo objeto en cada paquete (PERFORMANCE)
			consumerPortAddress= new PortAddress(InetAddress.getByAddress(new byte[]{a1,a2,a3,a4}),Message.paramFromPacket(input, 1));			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}

		byte b1=(byte)Message.paramFromPacket(input, 7);
		byte b2=(byte)Message.paramFromPacket(input, 8);
		byte b3=(byte)Message.paramFromPacket(input, 9);
		byte b4=(byte)Message.paramFromPacket(input,10);
		
		this.setSourceSpotId(Message.paramFromPacket(input, 11));
		
		try {
			producerPortAddress= new PortAddress(InetAddress.getByAddress(new byte[]{b1,b2,b3,b4}),Message.paramFromPacket(input, 6));			
		} catch (UnknownHostException e) { 
			e.printStackTrace();
		}
	}	


	@Override
	public void toBytes(byte[] output) {
		Message.setMessageId(output, MessageIdAttachConsumer);
		Message.paramFromPacket(output, 1, consumerPortAddress.port());
		
		byte[] a=consumerPortAddress.address().getAddress();
		Message.paramFromPacket(output, 2,a[0]);
		Message.paramFromPacket(output, 3,a[1]);
		Message.paramFromPacket(output, 4,a[2]);
		Message.paramFromPacket(output, 5,a[3]);
		
		Message.paramFromPacket(output, 6, producerPortAddress.port());

		byte[] b=consumerPortAddress.address().getAddress();
		Message.paramFromPacket(output, 7,b[0]);
		Message.paramFromPacket(output, 8,b[1]);
		Message.paramFromPacket(output, 9,b[2]);
		Message.paramFromPacket(output,10,b[3]);
		
		Message.paramFromPacket(output, 11,getSourceSpotId());

	}
	
	public void consumerPortAddress(PortAddress a) {
		consumerPortAddress=a;
	}
	
	public PortAddress consumerPortAddress() {
		return consumerPortAddress;
	}

	public void producerPortAddress(PortAddress a) {
		producerPortAddress=a;
	}
	
	public PortAddress producerPortAddress() {
		return producerPortAddress;
	}

	private PortAddress consumerPortAddress;
	private PortAddress producerPortAddress;

	@Override
	public int toByteSize() {		
		return 13*4;
	}

}
